package com.cocolover2.andbase.mvpbase;

import com.cocolover2.andbase.http.api.ABaseApi;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;


/**
 * @param <V>代表view接口
 */
public abstract class AndBasePresenter<V extends IAndBaseMVPView> {

    private Reference<V> mViewRef;

    private CompositeDisposable mCompositeDisposable;


    public void attachView(V view) {         //建立关联
        mViewRef = new WeakReference<V>(view);
    }

    protected V getView() {
        return mViewRef.get();
    }

    public boolean isViewAttached() {
        return mViewRef != null && mViewRef.get() != null;
    }

    //该方法在activity或者Fragment的onDestory中调用
    public void detachView() {
        if (mCompositeDisposable != null)
            mCompositeDisposable.dispose();
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
    }


    public CompositeDisposable getCompositeDisposable() {
        if (this.mCompositeDisposable == null) {
            this.mCompositeDisposable = new CompositeDisposable();
        }
        return this.mCompositeDisposable;
    }

    public void addCompositeDisposable(Disposable s) {
        if (s != null)
            getCompositeDisposable().add(s);
    }

    /**
     * 获取API帮助子类
     */
    public abstract <A extends ABaseApi> A getApiHelper();

}
